package com.apanal.qlife.monitor.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.apanal.qlife.common.annotation.LogType;
import com.apanal.qlife.common.annotation.SystemLog;
import com.apanal.qlife.common.constants.Constants;
import com.apanal.qlife.common.util.PrettyMemoryUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 缓存监控器控制类
 * 
 * 
 * @author shuliangxing
 * 
 * @date 2015-10-13下午3:15:34
 */
@Controller
@RequestMapping("monitor/ehcache")
public class EhcacheMonitorController {

	@Autowired
	private CacheManager cacheManager;

	/**
	 * 缓存列表
	 * 
	 * @param model
	 * @return
	 */
	@SystemLog(module = "缓存监控", operation = "查询缓存", type = LogType.SELECT)
	@RequiresPermissions("monitor:ehcache:view")
	@RequestMapping()
	public String index(Model model) {
		model.addAttribute("cacheManager", cacheManager);
		return "monitor/ehcache/index";
	}

	/**
	 * 缓存键列表
	 * 
	 * @param cacheName
	 * @param searchText
	 * @param model
	 * @return
	 */
	@RequiresPermissions("monitor:ehcache:view")
	@RequestMapping("{cacheName}/detailList")
	public String details(
			@PathVariable("cacheName") String cacheName,
			@RequestParam(value = "searchText", required = false, defaultValue = "") String searchText,
			Model model) {
		model.addAttribute("cacheName", cacheName);
		List<?> allKeys = cacheManager.getCache(cacheName).getKeys();

		List<Object> showKeys = Lists.newArrayList();

		for (Object key : allKeys) {
			if (key.toString().contains(searchText)) {
				showKeys.add(key);
			}
		}

		model.addAttribute("keys", showKeys);
		model.addAttribute("searchText", searchText);

		return "monitor/ehcache/detailList";
	}

	/**
	 * 缓存对应key的详情
	 * 
	 * @param cacheName
	 * @param key
	 * @param model
	 * @return
	 */
	@RequiresPermissions("monitor:ehcache:view")
	@RequestMapping("{cacheName}/{key}/details")
	@ResponseBody
	public Object keyDetail(@PathVariable("cacheName") String cacheName,
			@PathVariable("key") String key, Model model) {
		Element element = cacheManager.getCache(cacheName).get(key);

		String dataPattern = "yyyy-MM-dd hh:mm:ss";
		Map<String, Object> data = Maps.newHashMap();
		data.put("objectValue", element.getObjectValue().toString());
		data.put("size",
				PrettyMemoryUtils.prettyByteSize(element.getSerializedSize()));
		data.put("hitCount", element.getHitCount());

		Date latestOfCreationAndUpdateTime = new Date(
				element.getLatestOfCreationAndUpdateTime());
		data.put("latestOfCreationAndUpdateTime", DateFormatUtils.format(
				latestOfCreationAndUpdateTime, dataPattern));
		Date lastAccessTime = new Date(element.getLastAccessTime());
		data.put("lastAccessTime",
				DateFormatUtils.format(lastAccessTime, dataPattern));
		if (element.getExpirationTime() == Long.MAX_VALUE) {
			data.put("expirationTime", "不过期");
		} else {
			Date expirationTime = new Date(element.getExpirationTime());
			data.put("expirationTime",
					DateFormatUtils.format(expirationTime, dataPattern));
		}

		data.put("timeToIdle", element.getTimeToIdle());
		data.put("timeToLive", element.getTimeToLive());
		data.put("version", element.getVersion());

		return data;
	}

	/**
	 * 移除缓存
	 * 
	 * @param cacheName
	 * @param key
	 * @return
	 */
	@SystemLog(module = "缓存监控", operation = "移除缓存", type = LogType.DELETE)
	@RequiresPermissions("monitor:ehcache:delete")
	@RequestMapping("{cacheName}/{key}/delete")
	@ResponseBody
	public Object delete(@PathVariable("cacheName") String cacheName,
			@PathVariable("key") String key) {
		Cache cache = cacheManager.getCache(cacheName);
		cache.remove(key);

		return Constants.DEFAULT_MSG_SUCCESS;
	}

	/**
	 * 清空缓存
	 * 
	 * @param cacheName
	 * @return
	 */
	@SystemLog(module = "缓存监控", operation = "清空缓存", type = LogType.DELETE)
	@RequiresPermissions("monitor:ehcache:clear")
	@RequestMapping("{cacheName}/clear")
	@ResponseBody
	public Object clear(@PathVariable("cacheName") String cacheName) {
		Cache cache = cacheManager.getCache(cacheName);
		cache.clearStatistics();
		cache.removeAll();

		return Constants.DEFAULT_MSG_SUCCESS;
	}
}